/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.sentry.servlet;

import com.jakewharton.nopen.annotation.Open;

import io.sentry.Breadcrumb;
import io.sentry.HubAdapter;
import io.sentry.IHub;
import io.sentry.util.Objects;

import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;

import org.jetbrains.annotations.NotNull;

/**
 * This request listener pushes a new scope into sentry that enriches a Sentry event with the
 * details about the current request upon sending.
 */
@Open
public class SentryServletRequestListener implements ServletRequestListener {

    private final IHub hub;

    public SentryServletRequestListener(@NotNull IHub hub) {
        this.hub = Objects.requireNonNull(hub, "hub is required");
    }

    public SentryServletRequestListener() {
        this(HubAdapter.getInstance());
    }

    @Override
    public void requestDestroyed(@NotNull ServletRequestEvent servletRequestEvent) {
        hub.popScope();
    }

    @Override
    public void requestInitialized(@NotNull ServletRequestEvent servletRequestEvent) {
        hub.pushScope();

        final ServletRequest servletRequest = servletRequestEvent.getServletRequest();
        if (servletRequest instanceof HttpServletRequest) {
            final HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;

            hub.addBreadcrumb(Breadcrumb.http(httpRequest.getRequestURI(), httpRequest.getMethod()));

            hub.configureScope(
                scope -> {
                    scope.addEventProcessor(new SentryRequestHttpServletRequestProcessor(httpRequest));
                });
        }
    }
}
